import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8001',
  timeout: 300000, // 5分钟超时，适应流式响应
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    console.log('发送请求:', config)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('收到响应:', response)
    return response
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

class ApiService {
  /**
   * 发送消息到后端
   * @param {string} apiType - API类型
   * @param {string} message - 消息内容
   * @param {File} file - 文件（可选）
   * @returns {Promise<string>} 响应内容
   */
  async sendMessage(apiType, message, file = null) {
    try {
      switch (apiType) {
        case 'simple':
          return await this.simpleChat(message)
        case 'substrate':
          return await this.substrateChat(message)
        case 'assistant':
          return await this.assistantChat(message)
        case 'assistantSystem':
          return await this.assistantSystemChat(message)
        case 'assistantStream':
          return await this.assistantStreamChat(message)
        case 'img2text':
          return await this.img2text(message, file)
        case 'img2text2':
          return await this.img2textStream(message, file)
        default:
          throw new Error('未知的API类型')
      }
    } catch (error) {
      console.error('API调用失败:', error)
      throw new Error(error.response?.data?.message || error.message || '请求失败')
    }
  }

  /**
   * 简单聊天
   */
  async simpleChat(message) {
    const response = await api.get(`/chat/simple/demo/${encodeURIComponent(message)}`)
    console.log(response)
    return response.data
  }

  /**
   * 底层聊天
   */
  async substrateChat(message) {
    const response = await api.get(`/chat/substrate/demo/${encodeURIComponent(message)}`)
    return response.data
  }

  /**
   * AI助手聊天
   */
  async assistantChat(message) {
    const response = await api.get(`/chat/assistant/demo/${encodeURIComponent(message)}`)
    return response.data
  }

  /**
   * 系统助手聊天
   */
  async assistantSystemChat(message) {
    const response = await api.get(`/chat/assistantSystem/demo/${encodeURIComponent(message)}`)
    return response.data
  }

  /**
   * 流式助手聊天
   */
  async assistantStreamChat(message) {
    return new Promise((resolve, reject) => {
      let result = ''
      let hasData = false

      const eventSource = new EventSource(`http://localhost:8001/chat/assistantStream/demo/${encodeURIComponent(message)}`)

      eventSource.onopen = function() {
        console.log('SSE连接已建立')
      }

      eventSource.onmessage = function(event) {
        console.log('收到SSE数据:', event.data)
        hasData = true
        if (event.data && event.data !== '[DONE]') {
          result += event.data
        }
      }

      eventSource.onerror = function() {
    
        eventSource.close()

        // 如果已经有数据，认为是正常结束
        if (hasData && result) {
          resolve(result)
        } else {
          reject(new Error('流式连接失败，请检查后端服务是否正常运行'))
        }
      }

      // 监听连接关闭
      eventSource.addEventListener('close', function() {
        console.log('SSE连接关闭')
        eventSource.close()
        if (result) {
          resolve(result)
        }
      })

      // 设置超时
      const timeout = setTimeout(() => {
        console.log('SSE连接超时')
        eventSource.close()
        if (result) {
          resolve(result)
        } else {
          reject(new Error('请求超时'))
        }
      }, 300000) // 5分钟超时

      // 清理超时
      eventSource.addEventListener('close', () => {
        clearTimeout(timeout)
      })
    })
  }

  /**
   * 图片转文本
   */
  async img2text(message, file) {
    if (!file) {
      throw new Error('请选择图片文件')
    }

    const formData = new FormData()
    formData.append('msg', message)
    formData.append('file', file)

    const response = await api.post('/multi/img2text', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  }

  /**
   * 流式图片转文本
   */
  async img2textStream(message, file) {
    if (!file) {
      throw new Error('请选择图片文件')
    }

    const formData = new FormData()
    formData.append('msg', message)
    formData.append('file', file)

    const response = await api.post('/multi/img2text2', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  }
}

export default new ApiService()
